import { queryUser } from '@/services/assessManage/user/UserController';
import services from '@/services/login';
import { storage } from '@/utils/Storage';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginFormPage, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { message } from 'antd';
import type { FC } from 'react';
// import { useState } from 'react';
import routers from '../../../config/routes';

const { login } = services.LoginController;

const Login: FC = () => {
  const { refresh } = useModel('@@initialState');

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        backgroundImageUrl="https://gw.alipayobjects.com/zos/rmsportal/FfdJeJRQWjEeGTpqgBKj.png"
        logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        title="论文在线管理系统"
        // subTitle="网站"
        onFinish={async (values: any) => {
          const res = await login({ ...values });

          if (res.code === 200) {
            storage.set('token', res?.data?.token);
            const resUser = await queryUser({ id: res?.data?.userId });

            if (resUser?.code === 200) {
              storage.set('userInfo', resUser?.data);
              message.success(res.message || '登录成功');
              // history.push('/home');
              const currentUser = resUser?.data;
              const authArr =
                currentUser?.role?.map((item) => item?.compon).flat(Infinity) ||
                [];
              console.log('看看authArr', authArr);
              const newAuthArr = authArr?.map((item: Compon.ComponEntity) => {
                if (item?.name?.includes('half')) {
                  return item?.name?.substring(0, item?.name.length - 5);
                }
                return item?.name;
              });
              console.log('看看newAuthArr', newAuthArr);
              /** 登录进入有权限的页面处理 */
              const relAuthArr = Array.from(new Set(newAuthArr));
              let auhtPath: string = '/';
              const relRoute: any[] = [];
              const flatRoute = (data: typeof routers) => {
                data?.forEach?.((item) => {
                  relRoute.push(item);
                  if (item?.routes) {
                    relRoute.push(item?.routes);
                  }
                });
              };
              flatRoute(routers);
              const getRouteIndex = (authArrParams: any[]) =>
                relRoute
                  .flat(Infinity)
                  ?.findIndex((item) => item?.title === authArrParams?.[0]);
              const routeIndex = getRouteIndex(relAuthArr);
              if (relRoute.flat(Infinity)?.[routeIndex]?.routes) {
                const indexArr = relAuthArr?.filter((item) => {
                  return (
                    relRoute
                      .flat(Infinity)
                      ?.[routeIndex]?.routes?.findIndex(
                        (citem: { title: string }) => citem?.title === item,
                      ) !== -1
                  );
                });
                auhtPath =
                  relRoute.flat(Infinity)?.[getRouteIndex(indexArr)]?.path;
              } else {
                auhtPath = relRoute.flat(Infinity)?.[routeIndex]?.path;
              }
              if ((currentUser?.role || [])?.length === 0) {
                auhtPath = '/';
              }
              history.push(auhtPath);
              refresh();
              window?.location.reload();
            }
          }
        }}
      >
        <div style={{ paddingTop: '30px' }}>
          <ProFormText
            name="js_number"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={'prefixIcon'} />,
            }}
            placeholder={'学号/工号: admin or user'}
            rules={[
              {
                required: true,
                message: '请输入学号/工号!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={'prefixIcon'} />,
            }}
            placeholder={'密码: admin'}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
        </div>
      </LoginFormPage>
    </div>
  );
};

export default Login;
